package com.itzyf.pokemondata.activity.rank

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.activity.panel.PanelDetailActivity
import com.itzyf.pokemondata.bean.DbPokemon
import com.itzyf.pokemondata.bean.PokemonDo
import com.itzyf.pokemondata.bean.RankDo
import com.itzyf.pokemondata.utils.OnRefreshListener
import com.itzyf.pokemondata.utils.setOnRefreshListener
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_list_filter2.*
import kotlinx.android.synthetic.main.activity_list_filter2.ivStar
import kotlinx.android.synthetic.main.activity_list_filter2.mBtnSearch
import kotlinx.android.synthetic.main.activity_list_filter2.mSearchView
import kotlinx.android.synthetic.main.activity_list_filter2.pull_to_refresh
import kotlinx.android.synthetic.main.activity_list_filter2.rv_list
import kotlinx.android.synthetic.main.activity_list_star.*
import org.litepal.LitePal
import java.util.*


/**
 * @author 依风听雨
 * @version 创建时间：2019/01/09 09:13
 */
class RankActivity : BaseActivity() {
    var mDatas: MutableList<RankDo?> = ArrayList()
    var index = 0
    private lateinit var mAdapter: QuickAdapter
    var queryProperty = ""
    private lateinit var propertyList: Array<String>

    private var parameter: String = ""
    private var isStar = false

    override fun handlerActivity() {
        val type = intent.getIntExtra("type", PokemonDo.HP)

        val title = when (type) {
            PokemonDo.HP -> "血量排行榜"
            PokemonDo.PA -> "物攻排行榜"
            PokemonDo.PD -> "物防排行榜"
            PokemonDo.SA -> "特攻排行榜"
            PokemonDo.SD -> "特防排行榜"
            PokemonDo.SPEED -> "速度排行榜"
            else -> "排行榜"
        }
        setTitle(title)

        parameter = when (type) {
            PokemonDo.HP -> "hp"
            PokemonDo.PA -> "pa"
            PokemonDo.PD -> "pd"
            PokemonDo.SA -> "sa"
            PokemonDo.SD -> "sd"
            PokemonDo.SPEED -> "speed"
            else -> "hp"
        }
        propertyList = resources.getStringArray(R.array.propertyList)
        mAdapter = QuickAdapter(R.layout.item_speed, mDatas)
        rv_list.layoutManager = LinearLayoutManager(this)
        rv_list.adapter = mAdapter
//        showProgressDialog()
        queryDatas()

        mAdapter.setOnLoadMoreListener({ queryDatas(index++) }, rv_list)

        pull_to_refresh.setOnRefreshListener(object : OnRefreshListener {
            override fun onRefresh() {
                index = 0
                queryDatas(index)
            }
        })

        mBtnSearch.setOnClickListener {
            val query = mSearchView.text.toString()
            queryDatas(query = query)
        }
        mSearchView.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val query = mSearchView.text.toString()
                queryDatas(query = query)
                return@OnEditorActionListener true
            }
            false
        })

        spProperty.setItems(propertyList.toList())
        spProperty.setOnItemSelectedListener { _, position, _, _ ->
            queryProperty = when (position) {
                1 -> "普"
                2 -> "格"
                3 -> "飞"
                5 -> "地"
                6 -> "岩"
                8 -> "鬼"
                14 -> "超"
                18 -> "妖"
                0 -> ""
                else -> propertyList[position]
            }
            index = 0
            queryDatas(index)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this@RankActivity, PanelDetailActivity::class.java)
            intent.putExtra("objId", mDatas[position]?.objectId)
            startActivity(intent)
        }

        ivStar.visibility = View.VISIBLE
        ivStar.setOnClickListener {
            isStar = !isStar
            ivStar.setImageResource(if (isStar) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp)
            index = 0
            queryDatas(index)
        }
    }

    override fun getContentViewId() = R.layout.activity_list_filter2

    override fun getToolbarTitle() = "排行榜"
    /**
     * 查询数据
     */
    fun queryDatas(index: Int = 0, pageSize: Int = 20, query: String = "") {
        var where = ""

        if (!TextUtils.isEmpty(query)) {
            where = "pokemonName like '%$query%'"
        }
        //属性筛选
        if (!TextUtils.isEmpty(queryProperty)) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where += "property like '%$queryProperty%'"
        }
        if (isStar) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where = "isStar = 1"
        }

        val dataList =
            LitePal
                .select("pokemonName", "objectId", parameter, "isLevel", "red1")
                .limit(pageSize)
                .offset(index * pageSize)
                .order("$parameter desc")
                .where(where)
                .find(DbPokemon::class.java)
        if (index == 0) {
            mDatas.clear()
            pull_to_refresh.finishRefresh()
        }

        for (obj in dataList) {
            val o = RankDo()
            o.pokemon = obj.pokemonName
            o.objectId = obj.objectId
            o.isLevel = obj.isLevel
            val aClass = obj.javaClass
            val field = aClass.getDeclaredField(parameter)
            field.isAccessible = true
            o.value = field.getInt(obj) + getRed(obj.red1)
            mDatas.add(o)
        }

        mDatas.sortByDescending { it?.value }

        if (dataList.size < pageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
        mAdapter.notifyDataSetChanged()

    }

    private fun getRed(red1: String?): Int {
        if (red1 == null || red1.isEmpty()) {
            return 0
        }
        val type = intent.getIntExtra("type", PokemonDo.HP)

        val split = red1.split(",")
        if (split.size == 6) {
            return when (type) {
                PokemonDo.HP -> split[0].toInt()
                PokemonDo.PA -> split[1].toInt()
                PokemonDo.PD -> split[2].toInt()
                PokemonDo.SA -> split[3].toInt()
                PokemonDo.SD -> split[4].toInt()
                PokemonDo.SPEED -> split[5].toInt()
                else -> 0
            }
        }
        return 0
    }


    internal inner class QuickAdapter(layoutResId: Int, data: List<RankDo?>) :
        BaseQuickAdapter<RankDo, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: RankDo?) {
            helper.setText(R.id.name, item?.pokemon)
            helper.setText(R.id.value, "${item?.value}")
            helper.setGone(R.id.ivUpdate, !item!!.isLevel)
        }
    }

}